<script lang="ts" setup>
import { getBasePath } from "@/api/common"
import { CODE_SUCCESS } from "@/utils/service"
import { ElMessage } from "element-plus"
import { computed, onMounted, ref } from "vue"

const props = defineProps({
  btnText: {
    type: String,
    default: "上传图片"
  },
  tip: {
    type: String,
    default: "图片不能超过 2M."
  },
  modelValue: String
})
const dialogImgVisible = ref<boolean>(false)

const handlePreview = async () => {
  if (props.modelValue) {
    dialogImgVisible.value = true
  } else {
    ElMessage.warning("没有可预览的图片")
  }
}
const emit = defineEmits(["update:modelValue"])

const handleRemove = () => {
  emit("update:modelValue", "")
}
const handleBeforeUpload = (file: any) => {
  return new Promise((resolve, reject) => {
    const isJPG = file.type === "image/jpeg" || "image/png"
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isJPG) {
      ElMessage.error("上传图片只能是 JPG、JPEG、PNG 格式!")
      reject()
    }
    if (!isLt2M) {
      ElMessage.error("上传图片大小不能超过 2MB!")
      reject()
    }
  })
}

const handleSuccess = async (response: any) => {
  if (response.code === CODE_SUCCESS) {
    emit("update:modelValue", response.data)
  }
}
const fileList = computed<any[]>(() => {
  let list: any[] = []
  if (props.modelValue) {
    list = [
      {
        name: props.modelValue.split("/").at(-1) || "",
        url: basePath.value + props.modelValue
      }
    ]
  }
  return list
})
const basePath = ref("")
onMounted(async () => {
  const { data } = await getBasePath()
  basePath.value = data
})
</script>

<template>
  <el-upload
    :value="props.modelValue"
    :file-list="fileList"
    class="upload-demo"
    action="/api/uploadImg"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :limit="1"
    :before-update="handleBeforeUpload"
    :on-success="handleSuccess"
  >
    <el-button type="primary">{{ btnText }}</el-button>
    <template #tip>
      <div class="el-upload__tip">{{ tip }}</div>
    </template>
  </el-upload>
  <el-dialog v-model="dialogImgVisible" title="图片预览" width="800" align-center>
    <img :src="basePath + props.modelValue" style="width: 700px" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogImgVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
